<?php
namespace app\appadmin\controller\v1;
use app\app\Appbase;

class Order extends Appbase 
{
	
	/**
    * 构造函数自动执行
    * @return null
    */
    public function __construct(){
    	if(request()->identity == 1){
      		return $this->ReError( '管理员不能进行当前操作！' );
    	}
		parent::__construct();
    }
	
	/**
	* 订单列表
	* /appadmin/v1/order/index
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function index($uid,$name='',$cate_id='',$type=1){
		$shopId = request()->shopId;
		try {
			$level = model('UserVip')->where('uid',$uid)->value('level');
			$model = model('goods')->setShop($shopId)->setUser($uid)->getModel();
			if( $type==2 ){
				$model = $model->where('type',"2");
			}else if($type==3){
				$model = $model->where('type',"1");
			}else{
				$model = $model->where('type','not in',"1,2");
			}
			$name && $model = $model->where('a.name','like',"%".$name."%");
			$cate_id && $model = $model->where('a.cate_id',$cate_id);
			$goods = $model->all();
			$data = [];
			foreach( $goods as $key => $g ){
				$goods[$key]['specs_list'] = $specsLlist = model('goods')->getGoodsSpecs($g,$shopId);
				foreach( $specsLlist as $k => $v ){
					$v['goods_name'] = $g['goods_name'] . ' / ' .$v['name'];
					$v['goods_type'] = $g['goods_type'];
					$data[] =  $v;
				}
			}
			return $this->ReSucess($data);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 结算
	* /app/v2/order/settlement
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function settlement($uid,$data,$coupon_id=0){
		$param = request() ->post();
		try {
			
			//获取用户信息
			if( !$user = model('user')->getInfo($uid) ){
				return $this->ReError('用户id无效！');
			};
			
			//添加购物车 - 获取购物车id
			$cartIds = [];
			foreach( json_decode($data,true) as $key => $val ){
				$cart = model('ShopCart')->setCartInc($uid,$val['goods_id'],$val['id'],$val['num']??1,1);
				if($cart === false){
					return $this->ReError( model('ShopCart')->errorInfo );
				}
				$cartIds[] = $cart['id'];
			}
			
			// TODO 确认订单
			$res = model('order')->setBill(true)->setCoupon($coupon_id)->confirm($cartIds,$user);
			
			return $this->ReSucess($res);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());
		}
	}
	
	
	/**
	* 确认
	* /appadmin/v1/order/confirm
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function confirm($orderKey){
		if(!trim($orderKey) ) return $this->ReError('orderKe不能为空！');
		$userId = request()->userId;
		$identity = request()->identity;
		
		try {
			
			$dbOrder = model('Order');
			if ( !$cacheOrderInfo = $dbOrder->getCacheOrderInfo($orderKey) ){
				return $this->ReError('订单信息已过期,请刷新当前页面！');
        	}
        	
			//添加开单记录
			$uid = $cacheOrderInfo['userInfo']['id'];
			$bill = model('order_bill')->add($uid,$userId,$identity,request()->shopId);
			
			//生成订单
			$order = $dbOrder->setMark( request()->post('mark') )
	        	->setPayType('offline')
	        	->setBillId($bill['id'])
	        	->createOrder($orderKey);
	        	
	       	$res = $order && $dbOrder->paySuccess( $order->order_no, 'offline');
	       	if($res){
	       		$order->is_pay = 1;
	       		$order = $dbOrder->tidyOrder($order);
	       	}
	       	
	       	event('OrderCreated', $order); 	//订单创建成功事件
			return $this->ReSucess($order);
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
	
	
	/**
	* 确认
	* /appadmin/v1/order/lists
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function lists(){
		$userId = request()->userId;
		$identity = request()->identity;
		try {
			
			$res = model('order_bill')->alias('a')
				->leftJoin('order b','b.bill_id = a.id')
				->leftJoin('user_vip c','b.uid = a.uid')
				->field('b.id,b.order_no,b.type,b.add_time,b.uid,b.pay_price')
				->field('c.name,c.code')
				->where('a.add_identity',$identity)
				->where('a.add_uid',$userId)
				->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)
				->order('a.add_time','desc')
				->select();
				
			return $this->ReSucess($res);
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
	
	
	/**
	*获取订单明细
	* /app/v1/order/details
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function details($id){
		if(!$id){
			return $this->ReError('订单id不能为空！');
		}
		try {
			$result = model('order')->details($id);
			$result->user_info = model('user_vip')->where('uid',$result['uid'])->field('name,code')->find();
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
}



